<template>
  <ion-page>
      <ion-header>
          <ion-toolbar>
              <ion-buttons slot="start">
                  <ion-back-button :default-href="backUrl" @click="handleBack"></ion-back-button>
              </ion-buttons>  
              <ion-title class="title">{{ currentTriggerName }}</ion-title> 
              <ion-buttons slot="end">
                  <ion-button shape="round" fill="outline" @click="gotoValidate(currentTriggerName)">validate</ion-button>
              </ion-buttons>                     
          </ion-toolbar>    
      </ion-header>
      <ion-content>        
          <ion-card class="card" v-for="item in items" :key="item.id" 
                   :style="{ 'background-color': getCardColor(items1) }">
            <ion-card-content>
              <ion-grid >
                <ion-row>
                  <ion-col size="6">{{ 'MISSION  ' }}</ion-col>
                  <ion-col size="6" class="text">{{ item.triggerTelescopeName }}</ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="6" >{{ 'TRIGGER NAME  ' }}</ion-col>
                  <ion-col size="6" class="text">{{ item.triggerName }}</ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="6">{{ 'EVENT NAME  ' }}</ion-col>
                  <ion-col size="6" class="text">{{ items1.eventName}}</ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="6">{{ 'SVOM BURST ID  ' }}</ion-col>
                  <ion-col size="6" class="text">{{ items1.svomBurstId}}</ion-col>
                  <ion-col size="12"></ion-col>                                       
                  <ion-col size="6">{{ 'TYPE  ' }}</ion-col>  
                  <ion-col size="6" class="text">{{ item.triggerTypeName }}</ion-col>
                  <ion-col size="12"></ion-col> 
                  <ion-col size="6">{{ 'REAL  ' }}</ion-col>
                  <ion-col size="6" class="text" >{{ validate(items1.validated) }}</ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="2.5">{{ 'NOTE' }}</ion-col>
                  <ion-col size="9.5" class="note" >{{items1.note }}</ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="6">CHECK IN</ion-col>
                  <ion-col size="6" @click="openExternalPage" class="tool">
                    <ion-icon aria-hidden="true" :icon="buildOutline" ></ion-icon>
                    BA TOOLS</ion-col>
                  <ion-col size="12"></ion-col>
                  <div class="content" >
                    <ion-grid>
                      <ion-row>
                        <ion-col size="4">TRIGGER TIME:
                          <ion-icon style="font-size: 20px" aria-hidden="true" :icon="helpCircleOutline" button @click="showTooltip = true">
                            <ion-popover :is-open="showTooltip" @didDismiss="showTooltip = false" >
                              <ion-header class="bg" ><span>&nbsp;&nbsp;&nbsp;</span>1</ion-header>
                              <ion-content class="ion-padding">Trigger Time(T0),in UT,is retrived from the latest alert packet.</ion-content>
                            </ion-popover>
                           </ion-icon> 
                        </ion-col>
                        <ion-col size="8" class="text">{{ item.triggerTime }}</ion-col>
                        <ion-col size="12"></ion-col>                           
                        <ion-col size="4">{{ 'RA : ' }}
                          <ion-icon style="font-size: 20px" aria-hidden="true" :icon="helpCircleOutline" button @click="showTooltip1 = true">
                            <ion-popover :is-open="showTooltip1" @didDismiss="showTooltip1 = false" >
                              <ion-header class="bg" ><span>&nbsp;&nbsp;&nbsp;</span>2</ion-header>
                              <ion-content class="ion-padding">Coordinates(in J2000 epoch) and Err,are retrived from the latest packet.</ion-content>
                            </ion-popover>
                           </ion-icon>
                          </ion-col>
                        <ion-col size="8" class="text">{{ item.alertRaCenterStr }}</ion-col>
                        <ion-col size="12"></ion-col>
                        <ion-col size="4">{{ 'DEC : ' }}</ion-col>
                        <ion-col size="8" class="text">{{ item.alertDecCenterStr }}</ion-col>
                        <ion-col size="12"></ion-col>
                        <ion-col size="4">{{ 'ERROR : ' }}</ion-col>
                        <ion-col size="4" class="text">{{ convertToDegMin(item.alertLocalisationError) }} 
                        </ion-col>
                        <ion-col size="4">
                          <select v-model="selectedUnit" >
                            <option v-for="unit in units" :key="unit.value" :value="unit.value" >
                              {{ unit.value }}
                            </option>
                          </select>
                        </ion-col>
                      </ion-row>  
                    </ion-grid>
                  </div>                                                        
                </ion-row>
              </ion-grid>
            </ion-card-content>
          </ion-card>   
          <ion-col size="12"><span>&nbsp;&nbsp;</span> NOTICE LIST:</ion-col>        
          <ion-card class="card" v-for="notice in notices" :key="notice.id">
            <ion-card-content>
              <ion-grid>
                <ion-row>
                  <ion-col size="4"> {{'ID:'}}</ion-col>
                  <ion-col size="8" class="text"> {{notice.id}} </ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="4">{{ 'TIME : ' }}</ion-col>
                  <ion-col size="8" class="text">{{ notice.deteTime }}</ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="4">{{ 'SUBJECT : ' }}</ion-col>
                  <ion-col size="7" class="text">{{ notice.subject }} </ion-col>
                  <ion-col size="1"><ion-icon class="eye"  aria-hidden="true" :icon="eyeOutline" button @click="goToContent(notice.id)"/></ion-col>
                  <ion-col size="12"></ion-col>
                  <ion-col size="4">{{ 'OBS/INST : ' }}</ion-col>
                  <ion-col size="8" class="text">{{ notice.inst }}</ion-col>                                           
                </ion-row>
              </ion-grid>
            </ion-card-content>
          </ion-card>   
      </ion-content>
  </ion-page>
  </template>
  
  <script setup>
  import service from '@/api/api'
  import service1 from '@/api/api'
  import { onMounted, computed } from 'vue';
  import { 
      IonContent,
      IonGrid,
      IonTitle,
      IonCard,
      IonIcon,
      IonPopover,
      IonButton,
      IonBackButton,
      IonCardContent,
      IonCol,    
      IonRow,
      IonPage,
      IonHeader,
      IonToolbar,
      IonButtons,
      } from '@ionic/vue';
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { useRoute } from 'vue-router';
  import { helpCircleOutline,eyeOutline,buildOutline } from 'ionicons/icons';
  
  const showTooltip = ref(false);
  const showTooltip1 = ref(false);
  const router = useRouter();
  const route = useRoute();
  
  // 使用计算属性获取当前triggerName
  const currentTriggerName = computed(() => {
    return route.params.triggerName || items1.value.triggerName || '';
  });
  
  // 返回URL
  const backUrl = computed(() => {
    return router.options.history.state.back || '/tabs/eventlist';
  });
  
  const items = ref([{
    triggerTelescopeName:'',
    alertRaCenterStr:'',
    alertLocalisationError:'',
    alertDecCenterStr:'',
    triggerName: '',
    triggerTypeName:'',
    alertTime: '',
    triggerTime:'',
    eventName:'',
    id:'',
  }]);
  
  const items1 = ref({
    svomBurstId:'',
    validated:'',
    eventName:'',
    triggerName:'',
    triggerTypeName:'',
    triggerId:'',
    note:''
  });
  
  const validate = (validated) => {
      if(validated === true){
        return 'Y';
      }else if(validated === false){
        return 'N';
      }else{
        return ' ';
      }
  }
  
  const fetchData = async () => {
    try {        
      const triggerName = currentTriggerName.value;
      if (!triggerName) {
        console.error('No triggerName provided');
        return;
      }
      
      const response = await service.post('/alertApi/getAlerts', 
        {length:1},
        { params: { triggerName } }
      );
      
      const response1 = await service.post('/alertApi/getTriggers',
        {length:1},
        { params: { triggerName } }
      );
      
      items.value = response.data.data.list || [];
      items1.value = response1.data.data.list[0] || {};
      
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  
  onMounted(() => {
    fetchData();
  });
  
  const notices = ref([{
    deteTime:'',
    subject:'',
    inst:'',
    cls:'',
    mission:'',
    id:'',
    triggerName:''
  }]);
  
  const fetchData1 = async () => {
    try {        
      const triggerName = currentTriggerName.value;
      if (!triggerName) {
        console.error('No triggerName provided');
        return;
      }
      
      const response = await service1.post('/alertApi/getNcs',
        {length:100},
        {params:{triggerName, cls:1}}
      );
      notices.value = response.data.data.list || [];
    } catch (error) {
      console.error('Error fetching data:',error);
    }
  };
  
  onMounted(() => {
    fetchData1();
  });
  
  const getCardColor = (items1) => {
    if (!items1 || !items1.triggerTypeName) return 'LightGreen';
    const triggerType = items1.triggerTypeName.toString().trim().toLowerCase();
    if (triggerType === 'other') {
      return 'LightSteelBlue';
    }
    switch (items1.triggerTelescopeName) {
      case 'SVOM':
        return 'Orange';
      case 'LIGO/Virgo':
        return 'Khaki';
      default:
        return 'LightGreen';
    }
  };
  
  const openExternalPage = () => {
    const url = 'https://www.svom.cn/BA/#/BACenter/Event/Detail?triggerId=4036'; 
    window.open(url, '_blank');
  };
  
  const handleBack = () => {
    router.push({ name: 'eventlist' });
};
  
  const gotoValidate = (triggerName) => {
    const eventName = items1.value.eventName || '';
    const svomBurstId = items1.value.svomBurstId || '';
    const triggerId = items1.value.triggerId || ''; 
    router.push({ 
      name: 'validatepage',
      params: {
        triggerName,
        eventName,
        svomBurstId,
        triggerId
      }
    });
  };
  
  const goToContent = (id) => { 
    router.push({
      name: 'contentpage',
      params:{id}
    });
  };   
  
  const selectedUnit = ref('DEG');
  const convertToDegMin = (alertLocalisationError) => {
    if (alertLocalisationError === null || alertLocalisationError === undefined) return '';
    
    const minute = alertLocalisationError * 1;
    const minutes = alertLocalisationError * 60;
    const minutes1 = alertLocalisationError * 3600;
    
    switch (selectedUnit.value) {
      case 'DEG':
        return ` ${minute.toFixed(4)}`;
      case 'MIN':
        return ` ${minutes.toFixed(4)}`;
      default:
        return ` ${minutes1.toFixed(4)}`;
    }
  };
  
  const unit = [
    { value: 'DEG' },
    { value: 'MIN'},
    { value: 'SEC' },
  ];
  const units = ref(unit);
  </script>
  
  <style scoped>
  .content{
    background-color: white;
   } 
  .card {
    font-family: 'Arial', sans-serif;
    color: black;
  }
  .bg{
    background-color: gold;
  } 
  .text{
    background-color:rgb(188, 187, 187);
  } 
  .eye{
      background-color:NavajoWhite;
    }
  .tool{
    background-color: black;
    color:darksalmon;
  }
  .title{
    text-align: center;
  }
  .note{
    background-color: white;  
   } 
  </style>